<template>
  <n-modal
    v-model:show="visible"
    preset="card"
    :title="title"
    size="huge"
    :bordered="false"
    :mask-closable="false"
    @after-leave="handleClose"
  >
    <div class="model-container">
      <n-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-align="left"
        label-placement="left"
        label-width="70"
      >
        <n-form-item label="名称" path="spot">
          <n-input v-model:value="formData.spot" />
        </n-form-item>
        <n-form-item label="类型" path="type">
          <n-select v-model:value="formData.type" :options="typeOptions" />
        </n-form-item>
        <n-form-item label="地址" path="addr">
          <n-input v-model:value="formData.addr" />
        </n-form-item>
        <n-form-item label="开放时间">
          从
          <n-time-picker clearable v-model:value="start_time" format="HH:mm" />
          至
          <n-time-picker clearable v-model:value="end_time" format="HH:mm" />
        </n-form-item>

        <n-form-item label="官网">
          <n-input v-model:value="formData.url" />
        </n-form-item>
        <n-form-item label="电话">
          <n-input v-model:value="formData.tel" />
        </n-form-item>

        <n-form-item label="建议参观时长">
          <n-input v-model:value="formData.visit_time" />
        </n-form-item>

        <n-form-item label="图片" path="imgs">
          <n-upload
            v-model:file-list="fileList"
            list-type="image-card"
            :custom-request="customRequest"
            @remove="uploadRemove"
          >
            +
          </n-upload>
        </n-form-item>

        <n-form-item label="描述" path="desc">
          <n-input type="textarea" v-model:value="formData.desc" />
        </n-form-item>
        <n-form-item label="详情" path="detail">
          <n-input type="textarea" rows="10" v-model:value="formData.detail" />
        </n-form-item>
      </n-form>
    </div>

    <template #footer>
      <div class="footer">
        <n-button @click="handleClose" size="small" type="tertiary">
          取消
        </n-button>
        <n-button @click="handleSubmit" size="small" type="info">
          提交
        </n-button>
      </div>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import { upload, deleteImage, addScenic, updateScenic } from '@/api'
import { mapToLabelValue, timeToTimestamp, timestampToTime } from '@/utils'
import { SCENIC_TYPE } from '@/constant'
const message = useMessage()

const props = defineProps<{
  data: any
}>()
const visible = defineModel('visible')

const emit = defineEmits(['close', 'submit'])

const title = computed(() => (props.data ? '编辑' : '添加') + '景区')

const formData = ref({})
const fileList = ref<UploadFileInfo[]>([])

watch(visible, val => {
  val && handleShowModel()
})
const handleShowModel = () => {
  formData.value = props.data || {}

  if (props.data?.type) {
    formData.value.type = '' + formData.value.type
  } else {
    formData.value.type = '0'
  }

  if (props.data?.open_time) {
    const [start, end] = props.data?.open_time.split('-')
    start_time.value = timeToTimestamp(start)
    end_time.value = timeToTimestamp(end)
  } else {
    start_time.value = 0
    end_time.value = 0
  }

  fileList.value = props.data?.scenic_img?.map(i => {
    const id = i.split('/').pop()
    return {
      id,
      status: 'finished',
      url: i
    }
  })
}

const customRequest = async ({ file, onFinish, onError }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  const imgArr = await upload(formData).catch(() => {
    onError()
    fileList.value = fileList.value.filter(i => i.id !== file.id)
  })
  onFinish()
  fileList.value.forEach(i => {
    if (i.id === file.id) {
      i.url = imgArr[0]
    }
  })
}

const uploadRemove = async ({ file, fileList }) => {
  const res = await deleteImage({
    imgs: [file.url]
  })

  if (res) {
    fileList.value = fileList.filter(i => i.id !== file.id)
    message.success(res)
  }
}

const handleClose = () => {
  visible.value = false
  emit('close')
}

const formRef = ref(null)

const typeOptions = mapToLabelValue(SCENIC_TYPE)
const start_time = ref(0)
const end_time = ref(0)

const createRule = message => ({ required: true, trigger: 'blur', message })
const rules = {
  spot: [createRule('请填写景点名称')],
  type: [createRule('请选择景点类型')],
  addr: [createRule('请填写景点地址')],
  desc: [createRule('请填写景点描述')],
  detail: [createRule('请填写景点详情')],
  imgs: {
    required: true,
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (fileList.value.length === 0) {
        callback(new Error('请上传景点图片'))
      } else {
        callback()
      }
    }
  }
}

const handleSubmit = async e => {
  e.preventDefault()

  const valid = await formRef.value?.validate(errors => !errors)
  if (!valid) return

  formData.value.open_time = `${timestampToTime(
    start_time.value
  )}-${timestampToTime(end_time.value)}`
  formData.value.imgs = fileList.value.map(i => i.url)

  const res = formData.value.id
    ? await updateScenic({ ...formData.value, type: +formData.value.type })
    : await addScenic({ ...formData.value, type: +formData.value.type })
  message.success(res)

  handleClose()
  emit('submit')
}
</script>

<style scoped lang="scss">
.footer {
  text-align: center;
  .n-button {
    margin-left: 20px;
  }
}

.n-time-picker {
  margin: 0 10px;
}
</style>
